package cn.itcast.test.kafka;

import org.apache.kafka.clients.producer.*;
import org.junit.Test;

import java.util.Properties;

public class ProducerQuickStart {

    @Test
    public void sendMsg() {
        //2.kafka的配置信息
        Properties properties = new Properties();
        //2.1kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        //2.2发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 5);
        //2.3消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //2.4消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //1.生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3.发送消息
        ProducerRecord<String, String> record = new ProducerRecord<String, String>("order", "hello", "world");
        producer.send(record);
        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }

    @Test
    public void sendMsgAsync() {
        //2.kafka的配置信息
        Properties properties = new Properties();
        //2.1kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.130:9092");
        //2.2发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 5);
        //2.3消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //2.4消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"gzip");
        //ack返回机制
        // 0不等待消费者确认返回，直接继续发送 （数据不同步，但是最安全）
        // 1默认值，只要集群收到消息，生产者就会收到消费者的成功相应（默认策略）
        // all，需要等待所有参与的节点接收到消息，生产者才会收到服务器成功的相应（最安全，但是效率最低）
        properties.put(ProducerConfig.ACKS_CONFIG,"all");
        //1.生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //3.发送消息
        for (int i = 0; i < 100; i++) {
            ProducerRecord<String, String> record = new ProducerRecord<String, String>("order", "hello", "world");
            producer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e != null){
                        e.printStackTrace();
                    }
                }
            });
        }

        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }
}
